/******************************************************************************
 * @File name   :      MaintainMemberServiceImpl.java
 *
 * @Author      :      ANMA
 *
 * @Date        :      Jul 20, 2015
 *
 * @Copyright Notice: 
 * Copyright (c) 2014 DMS, Inc. All  Rights Reserved.
 * This software is published under the terms of the DMS Software
 * License version 1.0, a copy of which has been included with this
 * distribution in the LICENSE.txt file.
 * 
 * ----------------------------------------------------------------------------
 * Date                         Who         Version         Comments
 * Jul 20, 2015 6:10:04 PM    ANMA      1.0            Initial Version
 *****************************************************************************/
package com.cap.bts.crmdp.dealer.mars.service.impl;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.cap.bts.commonfunc.common.util.UserUtil;
import com.cap.bts.commonfunc.ge.dealer.service.IDealerService;
import com.cap.bts.crmdp.dealer.mars.service.IMarsMaintainMemberService;
import com.cap.bts.crmdp.dealer.member.constants.MaintainMemberConstants;
import com.cap.bts.crmdp.dealer.member.dao.IMaintainCarPlateDao;
import com.cap.bts.crmdp.dealer.member.dao.IMaintainMemberDao;
import com.cap.bts.crmdp.dealer.member.domain.CarPlateInfo;
import com.cap.bts.crmdp.dealer.member.domain.MemberInfo;
import com.cap.bts.crmdp.dealer.member.dto.MemberQueryDto;
import com.cap.bts.crmdp.dealer.member.dto.MemberResultsDto;
import com.cap.bts.crmdp.dealer.member.dto.MemberSubmitDto;
import com.cap.bts.crmdp.dealer.member.service.IMaintainCarPlateService;
import com.cap.bts.crmdp.webservice.dto.WSCrmCustomerDto;
import com.cap.bts.crmdp.webservice.dto.WSCrmCustomerResultDto;
import com.cap.bts.framework.common.constant.CommonConstants;
import com.cap.bts.framework.common.exception.AppException;
import com.cap.bts.framework.common.util.Utils;

/**
 * 
 */
@Transactional(rollbackFor = AppException.class)
@Service
public class MarsMaintainMemberServiceImpl implements IMarsMaintainMemberService {

    private static final Logger LOGGER = Logger.getLogger(MarsMaintainMemberServiceImpl.class);

    @Resource(name = "maintainMemberDao")
    private IMaintainMemberDao maintainMemberDao;

    @Autowired
    IMaintainCarPlateService maintainCarPlateService;

    @Autowired
    IDealerService dealerService;

    @Autowired
    IMaintainCarPlateDao carPlateDao;

    /*
     * Search customer info by phone number or car plate (non-Javadoc)
     * 
     * @see com.cap.bts.crmdp.dealer.member.service.IMaintainMemberService#
     * getMemberAndCarPlateByDto
     * (com.cap.bts.crmdp.dealer.member.dto.MemberQueryDto)
     */
    @Override
    public List<MemberResultsDto> getMemberAndCarPlateByDto(MemberQueryDto dto) throws AppException {

        List<Object[]> list = maintainMemberDao.getMemberAndCarPlateByDto(dto);
        List<MemberResultsDto> results = new ArrayList<MemberResultsDto>();
        if (list != null) {
            for (int i = 0; i < list.size(); i++) {
                MemberResultsDto memberResultsDto = new MemberResultsDto();

                Object[] obj = (Object[]) list.get(i);

                memberResultsDto.setMobilePhone((String) obj[0]);
                memberResultsDto.setMemberName((String) obj[1]);
                memberResultsDto.setCarPlate((String) obj[2]);
                memberResultsDto.setMemberCreateDate(Utils.formatDate(
                    CommonConstants.DATE_FORMAT_YYMMDD, (Date) obj[3]));
                memberResultsDto.setMemberStatus((String) obj[4]);
                memberResultsDto.setId(((BigInteger) obj[5]).longValue());
                // 追加显示套餐数量方法
                // mothed
                memberResultsDto.setExistPackageCountNum(getActivePackageCount(UserUtil
                    .getCurrentUser().getDealerId(), ((BigInteger) obj[5]).longValue(),
                    ((BigInteger) obj[6]).longValue()));
                results.add(memberResultsDto);
            }
        }

        return results;
    }

    /*
     * Search customer info by phone number or car plate (non-Javadoc)
     * 
     * @see com.cap.bts.crmdp.dealer.member.service.IMaintainMemberService#
     * getMemberAndCarPlateByDto
     * (com.cap.bts.crmdp.dealer.member.dto.MemberQueryDto)
     */
    @Override
    public List<MemberResultsDto> getMemberAndCarPlateWithPackageByDto(MemberQueryDto dto)
        throws AppException {

        List<Object[]> list = maintainMemberDao.getMemberAndCarPlateByDto(dto);
        List<MemberResultsDto> results = new ArrayList<MemberResultsDto>();
        if (list != null) {
            for (int i = 0; i < list.size(); i++) {
                MemberResultsDto memberResultsDto = new MemberResultsDto();

                Object[] obj = (Object[]) list.get(i);

                memberResultsDto.setMobilePhone((String) obj[0]);
                memberResultsDto.setMemberName((String) obj[1]);
                memberResultsDto.setCarPlate((String) obj[2]);
                memberResultsDto.setMemberCreateDate(Utils.formatDate(
                    CommonConstants.DATE_FORMAT_YYMMDD, (Date) obj[3]));
                memberResultsDto.setMemberStatus((String) obj[4]);
                memberResultsDto.setId(((BigInteger) obj[5]).longValue());
                //
                results.add(memberResultsDto);
            }
        }

        return results;
    }

    /*
     * create member info by name, phone number and car plate (non-Javadoc)
     * 
     * @see com.cap.bts.crmdp.dealer.member.service.IMaintainMemberService#
     * getCreateMemberByDto(com.cap.bts.crmdp.dealer.member.dto.MemberSubmitDto)
     */
    @Override
    public MemberResultsDto getCreateMemberByDto(MemberSubmitDto dto) throws AppException {

        MemberInfo memberInfo = new MemberInfo();
        MemberResultsDto result = new MemberResultsDto();
        CarPlateInfo carPlateInfo = null;

        try {

            memberInfo.setMemberName(dto.getMemberName());
            memberInfo.setMobilePhone(dto.getMobilePhone());
            memberInfo.setDealerId(dto.getDealerId());

            memberInfo = maintainMemberDao.save(memberInfo);

            result.setCarPlate(dto.getCarPlate());
            result.setId(memberInfo.getId());

            carPlateInfo = maintainCarPlateService.saveCarPlateInfo(result);

        } catch (Exception e) {
            LOGGER.debug(e);
            throw new AppException("ERROR", "");
        }

        result.setMemberName(memberInfo.getMemberName());
        result.setMobilePhone(memberInfo.getMobilePhone());
        result.setCarPlate(carPlateInfo.getCarPlate());
        result.setRegisterDate(Utils.formatDate(CommonConstants.DATE_FORMAT_YYMMDD,
            carPlateInfo.getRegisterDate()));
        result.setMemberStatus(carPlateInfo.getMemberStatus());

        return result;
    }

    @Override
    public List<MemberResultsDto> getMemberByMobilePhoneOrMemberId(MemberQueryDto dto)
        throws AppException {

        List<MemberResultsDto> list = maintainMemberDao.getMemberByMobilePhoneOrMemberId(dto);

        if (list != null && !list.isEmpty()) {
            return list;
        }
        return new ArrayList<MemberResultsDto>();
    }

    @Override
    public void getUpdateMemberName(MemberInfo info) throws AppException {
        maintainMemberDao.update(info);
    }

    /**
     * {@inheritDoc} overridden:
     * 
     * @Date : 2015年8月4日
     * @see com.cap.bts.crmdp.dealer.member.service.IMaintainMemberService#getMemberByCarPlate(com.cap.bts.crmdp.dealer.member.dto.MemberQueryDto)
     **/
    @Override
    public List<MemberResultsDto> getMemberByCarPlate(MemberQueryDto dto) throws AppException {
        List<MemberResultsDto> list = maintainMemberDao.getMemberByCarPlate(dto);
        if (list != null && !list.isEmpty()) {
            return list;
        }
        return new ArrayList<MemberResultsDto>();
    }

    /**
     * {@inheritDoc} overridden:
     * 
     * @Date : 2015年8月5日
     * @see com.cap.bts.crmdp.dealer.member.service.IMaintainMemberService#updateMemberNameByMemberResultsDto(com.cap.bts.crmdp.dealer.member.dto.MemberResultsDto)
     **/
    @Override
    public boolean updateMemberNameByMemberResultsDto(MemberResultsDto memberResultsDto)
        throws AppException {
        try {
            maintainMemberDao.updateMemberNameByMemberResultsDto(memberResultsDto);
            return true;
        } catch (Exception e) {
            throw new AppException("updateMemberNameByMemberResultsDto", e);
        }
    }

    /**
     * {@inheritDoc} overridden:
     * 
     * @Date : 2015年8月24日
     * @see com.cap.bts.crmdp.dealer.member.service.IMaintainMemberService#getActivePackageCount(java.lang.Long,
     *      java.lang.Long, java.lang.Long)
     **/
    @Override
    public int getActivePackageCount(Long dealerId, Long memberId, Long carId) throws AppException {
        return maintainMemberDao.getActivePackageCount(dealerId, memberId, carId);
    }

    /**
     * {@inheritDoc} overridden:
     * 
     * @Date : 2015年9月1日
     * @see com.cap.bts.crmdp.dealer.member.service.IMaintainMemberService#updateMemberMobileByMemberResultsDto(com.cap.bts.crmdp.dealer.member.dto.MemberResultsDto)
     **/
    @Override
    public boolean updateMemberMobileByMemberResultsDto(MemberResultsDto memberResultsDto)
        throws AppException {
        try {
            maintainMemberDao.updateMemberMobileByMemberResultsDto(memberResultsDto);
            return true;
        } catch (Exception e) {
            throw new AppException("updateMemberNameByMemberResultsDto", e);
        }
    }

    /**
     * {@inheritDoc} overridden:
     * 
     * @Date : 2015年9月6日
     * @see com.cap.bts.crmdp.dealer.member.service.IMaintainMemberService#removeMemberById(java.lang.Long)
     **/
    @Override
    public void removeMemberById(Long id) throws AppException {
        maintainMemberDao.remove(id);
    }

    @Override
    public WSCrmCustomerResultDto processCrmCustomerAndCarInfo(WSCrmCustomerDto dto) {
        WSCrmCustomerResultDto resultDto = new WSCrmCustomerResultDto();
        if (dto != null) { 
            try {
                MemberInfo memberInfo = maintainMemberDao.getMemberInfoByMarsInfo(
                    dto.getCustomerId(), dto.getServerCenter());

                if (memberInfo != null) {

                    memberInfo.setMemberName(dto.getCustomerName());
                    memberInfo.setMobilePhone(dto.getMobilePhone());

                    maintainMemberDao.update(memberInfo);

                } else if(dto.getAddFlag()) {
                    
                    MemberInfo newMemberInfo = new MemberInfo();
                    newMemberInfo.setMemberName(dto.getCustomerName());
                    newMemberInfo.setMobilePhone(dto.getMobilePhone());
                    newMemberInfo.setMarsDealerId(dto.getServerCenter());
                    newMemberInfo.setMarsMemberId(dto.getCustomerId());
                    newMemberInfo.setDealerId(Long.valueOf(dto.getServerCenter()));

                    memberInfo = maintainMemberDao.save(newMemberInfo);

                }
                
                if(StringUtils.isNotBlank(dto.getCarId())){                     
                    CarPlateInfo carPlateInfo = null;
                    CarPlateInfo existCarPlateInfo = carPlateDao.getCarPlateInfoByMarsInfo(dto.getCarId(), memberInfo.getId());
                    
                    if (existCarPlateInfo != null) {
                        carPlateInfo = existCarPlateInfo;
                    } else {
                        carPlateInfo = new CarPlateInfo();
                        carPlateInfo.setRegisterDate(new Date());
                        carPlateInfo.setMemberStatus("0");
                    }
                    carPlateInfo.setMemberId(memberInfo.getId());
                    carPlateInfo.setCarPlate(dto.getCarPlate());
                    carPlateInfo.setMarsCarId(dto.getCarId());
                    carPlateInfo.setLastUpdateDate(new Date());
                    if (Utils.notNullAndNegative(carPlateInfo.getId())) {
                        carPlateDao.update(carPlateInfo);
                    } else if(dto.getAddFlag()) {
                        carPlateDao.save(carPlateInfo);
                    }
                }
                
                resultDto.setStatusCode(MaintainMemberConstants.SUCCESS);
                resultDto.setResultMessage("success");
            } catch (Exception e) {
                LOGGER.error("processCrmCustomerAndCarInfo", e);
                resultDto.setStatusCode(MaintainMemberConstants.FAILURE);
                resultDto.setResultMessage(e.getLocalizedMessage());
                return resultDto;
            }
        } else {
            resultDto.setStatusCode(MaintainMemberConstants.FAILURE);
            resultDto.setResultMessage("Empty Data from Mars");
            return resultDto;
        }
        return resultDto;
    }

    /**
     * {@inheritDoc} overridden:
     * 
     * @Date : Oct 10, 2015
     * @see com.cap.bts.crmdp.dealer.member.service.IMaintainMemberService#getMemberById(java.lang.Long)
     **/
    @Override
    public MemberInfo getMemberById(Long id) throws AppException {
        return maintainMemberDao.findById(id);
    }

    /**
     * {@inheritDoc} 
     * overridden:
     * @Date        :      2015年10月23日
     * @see com.cap.bts.crmdp.dealer.member.service.IMaintainMemberService#getMemberByDealerId(java.lang.Long)
    **/
    @Override
    public MemberInfo getMemberByDealerId(Long dealerId,String marsMemberId) throws AppException {
        List<MemberInfo> memberInfoList = maintainMemberDao.getMemberByDealerId(dealerId,marsMemberId);
        MemberInfo memberInfo = new MemberInfo();
        if(memberInfoList != null && !memberInfoList.isEmpty()){
            memberInfo = memberInfoList.get(0);
        }
        return memberInfo;
    }

    /**
     * {@inheritDoc} 
     * overridden:
     * @Date        :      Oct 27, 2015
     * @see com.cap.bts.crmdp.dealer.member.service.IMaintainMemberService#getMemberByMarsMemeberId(java.lang.Long)
    **/
    @Override
    public MemberInfo getMemberByMarsInfo(String marsDealerId,String marsMemberId) throws AppException {
        List<MemberInfo> memberInfoList = maintainMemberDao.getMemberByMarsInfo(marsDealerId,marsMemberId);
        MemberInfo memberInfo = null;
        if(memberInfoList != null && !memberInfoList.isEmpty()){
            memberInfo = memberInfoList.get(0);
        }
        return memberInfo;
    }

}
